package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.mapper.ApUserRealnameMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceimpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //判断参数是否有效
        if (dto==null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }


        dto.checkParam();
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();

        wrapper.eq(dto.getStatus()!=null,ApUserRealname::getStatus,dto.getStatus());

        IPage result = page(page, wrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal());

        pageResponseResult.setData(result.getRecords());

        return pageResponseResult;
    }


    @Autowired
    ApUserMapper apUserMapper;

    @GlobalTransactional(timeoutMills = 60000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        // 1. 检查参数  id(认证信息)
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证信息id参数错误");
        }
        // 2. 查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        // 3. 判断当前实名认证的状态  (status = 1)
        if (userRealname.getStatus().intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"审核的状态错误");
        }
        // 4. 查询相关联的ap_user
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的app用户不存在");
        }
        // 5. 修改实名认证的状态
        userRealname.setUpdatedTime(new Date());
        userRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname); // 修改实名认证状态
        if(status.intValue() == 2){
            return ResponseResult.okResult();
        }
        // 校验姓名和身份证 是否真实
//        Map map = IdCardUtil.checkIdCard(userRealname.getIdno(), userRealname.getName());
//        Boolean success = (Boolean)map.get("success");
//        if(!success){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"身份信息校验失败:"+map.get("message"));
//        }
        // 6. 如果状态为 9
        // 6.1  开通自媒体账户
        WmUser wmUser = createWmUser(apUser);
        // 6.2  创建作者信息
        createAuthor(apUser,wmUser);
        // 报异常了
       // System.out.println(1/0);
        apUser.setFlag((short) 1);
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> findResult = articleFeign.findByUserId(apUser.getId());
        if (findResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        ApAuthor author = findResult.getData();
        if (author!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(author);
        if (saveResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 创建自媒体账户
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 1. 使用feign根据用户名称查询自媒体账户是否存在
        ResponseResult<WmUser> findResult = wemediaFeign.findByName(apUser.getName());
        if (findResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        WmUser wmUser = findResult.getData();
        if (wmUser!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已经存在");
        }
        // 2. 如果 不存在  创建自媒体账户
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId()); // apuserid
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (findResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        return saveResult.getData(); // 回去带有wmUserId的自媒体账户信息
    }

}
